package com.atguigu.spzx.manager.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.apache.poi.ss.formula.functions.T;

import java.io.IOException;
import java.util.List;

/**
 * Author:L枣
 * Date:2024/9/15
 */
public class ExcelListener<T> implements ReadListener<T> {

    //每隔100条数据，刷新一下数据库，防止数据太大，一次性提交到数据库导致内存溢出
    private static final int BATCH_COUNT = 100;

    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //构造传递Mapper，操作数据库
    private CategoryMapper categoryMapper;
    public ExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    //从第二行开始读取，把每一行读取的内容封装到对象中
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        //把每一行数据对象T放到放到cachedDataList中
        cachedDataList.add(t);
        if (cachedDataList.size() >= BATCH_COUNT) {
            //批量插入到数据库中
            saveData();
            //清空list，继续读取下一批数据
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        categoryMapper.batchInsert((List<CategoryExcelVo>)cachedDataList);
    }

}
